//DOM0 级事件处理程序
var btn1 = document.getElementById("myBtn1");
if (btn1 !== null) {
    btn1.onclick = function () {
        alert(this.id); //"myBtn1"
    };
}
//DOM2 级事件处理程序
var btn2 = document.getElementById("myBtn2");
// 。最后这个布尔值参数
// 如果是true，表示在捕获阶段调用事件处理程序；
// 如果是false，表示在冒泡阶段调用事件处理程序。
if (btn2 !== null) {
    var handler = function () {
        alert(this.id);
    };
    btn2.addEventListener("click", handler, false);
    btn2.addEventListener("click", function () {
        alert("Hello world!");
        //移除事件处理
        btn2.removeEventListener("click", handler, false);
    }, false);
}
// 大多数情况下，都是将事件处理程序添加到事件流的冒泡阶段，这样可以最大限度地兼容各种浏览
// 器。最好只在需要在事件到达目标之前截获它的时候将事件处理程序添加到捕获阶段。如果不是特别需
// 要，我们不建议在事件捕获阶段注册事件处理程序。

//IE事件处理程序
function ieTest() {
    var btn = document.getElementById("myBtn2");
    btn.attachEvent("onclick", function () {
        alert("Clicked");
    });
    // btn.detachEvent("onclick", handler);
}

function eventUtilTest() {
    var btn = document.getElementById("testBtn");
    var handler = function () {
        alert("Clicked");
    };
    EventUtil.addHandler(btn, "click", handler);
    // EventUtil.removeHandler(btn, "click", handler);
    btn.onclick = function (event) {
        //返回对event对象的引用
        event = EventUtil.getEvent(event);
        //返回事件的目标
        var target = EventUtil.getTarget(event);
        //取消事件的默认行为
        EventUtil.preventDefault(event);
        //首先尝试使用DOM 方法阻止事件流，否则就使用cancelBubble 属性
        EventUtil.stopPropagation(event);
    };
}

function handlerTest() {
    var btn = document.getElementById("testBtn");
    var handler = function (event) {
        switch (event.type) {
            case "click":
                alert("Clicked");
                break;
            case "mouseover":
                event.target.style.backgroundColor = "red";
                break;
            case "mouseout":
                event.target.style.backgroundColor = "";
                break;
        }
    };
    btn.onclick = handler;
    btn.onmouseover = handler;
    btn.onmouseout = handler;
}

//阻止特定事件的默认行为
function preventDefault() {
    var link = document.getElementById("myLink");
    link.onclick = function (event) {
        event.preventDefault();
    };
}

function stopPropagationTest() {
    var btn = document.getElementById("testBtn");
    btn.onclick = function (event) {
        alert("Clicked");
        event.stopPropagation();
    };
    document.body.onclick = function () {
        alert("Body clicked");
    };
}

function eventPhaseTest() {
// 。如果是在捕获阶段调用的事件处理程序，那么eventPhase 等于1；如果事件处理程序处于目标对象上，
// 则eventPhase 等于2；如果是在冒泡阶段调用的事件处理程序，eventPhase 等于3。这里要注意的是，尽管
// “处于目标”发生在冒泡阶段，但eventPhase 仍然一直等于2
    var btn = document.getElementById("testBtn");
    btn.onclick = function (event) {
        alert(event.eventPhase); //2
    };
    document.body.addEventListener("click", function (event) {
        alert(event.eventPhase); //1
    }, true);
    document.body.onclick = function (event) {
        alert(event.eventPhase); //3
    };
}

function imageLoadTest() {
    EventUtil.addHandler(window, "load", function () {
        var image = document.createElement("img");
        EventUtil.addHandler(image, "load", function (event) {
            event = EventUtil.getEvent(event);
            alert(EventUtil.getTarget(event).src);
        });
        document.body.innerHTML += "<br>";
        document.body.appendChild(image);
        image.src = "../file/logo.png";
    });
}

function scriptLoadTest() {
    EventUtil.addHandler(window, "load", function () {
        var script = document.createElement("script");
        EventUtil.addHandler(script, "load", function (event) {
            alert("Loaded");
        });
        script.src = "../js/ch12.js";
        document.body.appendChild(script);
    });
}

function linkLoadTest() {
    EventUtil.addHandler(window, "load", function () {
        var link = document.createElement("link");
        link.type = "text/css";
        link.rel = "stylesheet";
        EventUtil.addHandler(link, "load", function (event) {
            console.log("css loaded");
        });
        link.href = "../file/example.css";
        document.getElementsByTagName("head")[0].appendChild(link);
    });
}

function unloadTest() {
    EventUtil.addHandler(window, "unload", function (event) {
        alert("Unloaded");
    });
}

function resizeTest() {
    EventUtil.addHandler(window, "resize", function (event) {
        alert("Resized");
    });
}

function scrollTest() {
    EventUtil.addHandler(window, "scroll", function (event) {
        if (document.compatMode === "CSS1Compat") {
            console.log(document.documentElement.scrollTop);
        } else {
            console.log(document.body.scrollTop);
        }
    });
}

//在显示区域的坐标
function clientXYTest() {
    var div = document.getElementById("myDiv");
    EventUtil.addHandler(div, "click", function (event) {
        event = EventUtil.getEvent(event);
        console.log("Client coordinates: " + event.clientX + "," + event.clientY);
    });
}

//在页面的坐标，在页面没有滚动的情况下，pageX 和pageY 的值与clientX 和clientY 的值相等。
function pageXYTest() {
    var div = document.getElementById("myDiv");
    EventUtil.addHandler(div, "click", function (event) {
        event = EventUtil.getEvent(event);
        console.log("Page coordinates: " + event.pageX + "," + event.pageY);
    });
}

//IE8 及更早版本不支持事件对象上的页面坐标
function pageXYTest2() {
    var div = document.getElementById("myDiv");
    EventUtil.addHandler(div, "click", function (event) {
        event = EventUtil.getEvent(event);
        var pageX = event.pageX,
            pageY = event.pageY;
        if (pageX === undefined) {
            pageX = event.clientX + (document.body.scrollLeft ||
                document.documentElement.scrollLeft);
        }
        if (pageY === undefined) {
            pageY = event.clientY + (document.body.scrollTop ||
                document.documentElement.scrollTop);
        }
        alert("Page coordinates: " + pageX + "," + pageY);
    });
}

function screenXYTest() {
    var div = document.getElementById("myDiv");
    EventUtil.addHandler(div, "click", function (event) {
        event = EventUtil.getEvent(event);
        alert("Screen coordinates: " + event.screenX + "," + event.screenY);
    });
}

function supportFocusEvent() {
    var isSupported = document.implementation.hasFeature("FocusEvent", "3.0");
}

function keyTest() {
    var div = document.getElementById("myDiv");
    EventUtil.addHandler(div, "click", function (event) {
        event = EventUtil.getEvent(event);
        var keys = [];
        if (event.shiftKey) {
            keys.push("shift");
        }
        if (event.ctrlKey) {
            keys.push("ctrl");
        }
        if (event.altKey) {
            keys.push("alt");
        }
        if (event.metaKey) {
            keys.push("meta");
        }
        alert("Keys: " + keys.join(","));
    });
}

function mouseoutTest() {
    var div = document.getElementById("myDiv");
    EventUtil.addHandler(div, "mouseout", function (event) {
        event = EventUtil.getEvent(event);
        var target = EventUtil.getTarget(event);
        var relatedTarget = EventUtil.getRelatedTarget(event);
        alert("Moused out of " + target.tagName + " to " + relatedTarget.tagName);
    });
}

function getButtonTest() {
    var div = document.getElementById("myDiv");
    EventUtil.addHandler(div, "mousedown", function (event) {
        event = EventUtil.getEvent(event);
        alert(EventUtil.getButton(event));
    });
}

function mousewheelTest() {
    EventUtil.addHandler(document, "mousewheel", function (event) {
        event = EventUtil.getEvent(event);
        console.log(event.wheelDelta);
    });
}

function keyupTest() {
    var textbox = document.getElementById("myText");
    EventUtil.addHandler(textbox, "keyup", function (event) {
        event = EventUtil.getEvent(event);
        console.log(event.keyCode);
    });
}

function keypressTest() {
    var textbox = document.getElementById("myText");
    EventUtil.addHandler(textbox, "keypress", function (event) {
        event = EventUtil.getEvent(event);
        //获取按下按键的字符编码
        console.log(EventUtil.getCharCode(event));
    });
}

function removeTest() {
    EventUtil.addHandler(window, "load", function (event) {
        var list = document.getElementById("myList");
        EventUtil.addHandler(document, "DOMSubtreeModified", function (event) {
            console.log(event.type);
            console.log(event.target);
        });
        EventUtil.addHandler(document, "DOMNodeRemoved", function (event) {
            console.log(event.type);
            console.log(event.target);
            console.log(event.relatedNode);
        });
        EventUtil.addHandler(list.firstChild, "DOMNodeRemovedFromDocument", function (event) {
            console.log(event.type);
            console.log(event.target);
        });
        list.parentNode.removeChild(list);
    });
}

function appendChildTest() {
    EventUtil.addHandler(window, "load", function (event) {
        var list = document.getElementById("myList");
        var item = document.createElement("li");
        item.appendChild(document.createTextNode("Item 4"));
        EventUtil.addHandler(document, "DOMSubtreeModified", function (event) {
            console.log(event.type);
            console.log(event.target);
        });
        EventUtil.addHandler(document, "DOMNodeInserted", function (event) {
            console.log(event.type);
            console.log(event.target);
            console.log(event.relatedNode);
        });
        EventUtil.addHandler(item, "DOMNodeInsertedIntoDocument", function (event) {
            console.log(event.type);
            console.log(event.target);
        });
        list.appendChild(item);
    });
}

function contextmenuTest() {
    EventUtil.addHandler(window, "load", function (event) {
        var div = document.getElementById("myDiv");
        if (div !== null) {
            EventUtil.addHandler(div, "contextmenu", function (event) {
                event = EventUtil.getEvent(event);
                //阻止默认处理事件
                EventUtil.preventDefault(event);
                var menu = document.getElementById("myMenu");
                menu.style.left = event.clientX + "px";
                menu.style.top = event.clientY + "px";
                menu.style.visibility = "visible";
            });
            EventUtil.addHandler(document, "click", function (event) {
                document.getElementById("myMenu").style.visibility = "hidden";
            });
        }
    });
}

function beforeunloadTest() {
    EventUtil.addHandler(window, "beforeunload", function (event) {
        event = EventUtil.getEvent(event);
        var message = "I'm really going to miss you if you go.";
        event.returnValue = message;
        return message;
    });
}

function orientationTest() {
    EventUtil.addHandler(window, "load", function (event) {
        var div = document.getElementById("myDiv");
        div.innerHTML = "Current orientation is " + window.orientation;
        EventUtil.addHandler(window, "orientationchange", function (event) {
            div.innerHTML = "Current orientation is " + window.orientation;
        });
    });
}

function deviceorientationTest() {
    EventUtil.addHandler(window, "deviceorientation", function (event) {
        var myDiv = document.getElementById("myDiv");
        if (myDiv !== null) {
            myDiv.innerHTML = "Alpha=" + event.alpha + ", Beta=" + event.beta +
                ", Gamma=" + event.gamma + "<br>";
        }
    });
}

function touchTest() {
    function handleTouchEvent(event) {
        //只跟踪一次触摸
        if (event.touches.length === 1) {
            var output = document.getElementById("myDiv");
            switch (event.type) {
                case "touchstart":
                    output.innerHTML = "Touch started (" + event.touches[0].clientX +
                        "," + event.touches[0].clientY + ")";
                    break;
                case "touchend":
                    output.innerHTML += "<br>Touch ended (" +
                        event.changedTouches[0].clientX + "," +
                        event.changedTouches[0].clientY + ")";
                    break;
                case "touchmove":
                    event.preventDefault(); //阻止滚动
                    output.innerHTML += "<br>Touch moved (" +
                        event.changedTouches[0].clientX + "," +
                        event.changedTouches[0].clientY + ")";
                    break;
            }
        }
    }

    EventUtil.addHandler(document, "touchstart", handleTouchEvent);
    EventUtil.addHandler(document, "touchend", handleTouchEvent);
    EventUtil.addHandler(document, "touchmove", handleTouchEvent);
}

function gestureTest() {
    function handleGestureEvent(event) {
        var output = document.getElementById("myDiv");
        switch (event.type) {
            case "gesturestart":
                output.innerHTML = "Gesture started (rotation=" + event.rotation +
                    ",scale=" + event.scale + ")";
                break;
            case "gestureend":
                output.innerHTML += "<br>Gesture ended (rotation=" + event.rotation +
                    ",scale=" + event.scale + ")";
                break;
            case "gesturechange":
                output.innerHTML += "<br>Gesture changed (rotation=" + event.rotation +
                    ",scale=" + event.scale + ")";
                break;
        }
    }

    document.addEventListener("gesturestart", handleGestureEvent, false);
    document.addEventListener("gestureend", handleGestureEvent, false);
    document.addEventListener("gesturechange", handleGestureEvent, false);
}

//事件委托 减少性能消耗
function eventProxyTest() {
    var list = document.getElementById("myList");
    EventUtil.addHandler(list, "click", function (event) {
        event = EventUtil.getEvent(event);
        var target = EventUtil.getTarget(event);
        switch (target.id) {
            case "item1":
                document.title = "I changed the document's title";
                break;
            case "item2":
                location.href = "https://www.baidu.com";
                break;
            case "item3":
                alert("item3");
                break;
        }
    });
}

function MouseEventsTest() {
    var btn = document.getElementById("myBtn1");
    //创建事件对象
    var event = document.createEvent("MouseEvents");
    //初始化事件对象
    event.initMouseEvent("click", true, true, document.defaultView, 0, 0, 0, 0, 0,
        false, false, false, false, 0, null);
    //触发事件
    btn.dispatchEvent(event);
}

function fireKeyEvent(el, evtType, keyCode) {
    var doc = el.ownerDocument,
        win = doc.defaultView || doc.parentWindow,
        evtObj;
    // debugger;
    if (doc.createEvent) {
        if (win.KeyEvent) {//firefox 浏览器下模拟事件
            evtObj = doc.createEvent('KeyEvents');
            evtObj.initKeyEvent(evtType, true, true, win, false, false, false, false, keyCode, 0);
        } else {//chrome 浏览器下模拟事件
            evtObj = doc.createEvent('UIEvents');
            Object.defineProperty(evtObj, 'keyCode', {
                get: function () {
                    return this.keyCodeVal;
                }
            });
            Object.defineProperty(evtObj, 'which', {
                get: function () {
                    return this.keyCodeVal;
                }
            });
            evtObj.initUIEvent(evtType, true, true, win, 1);
            evtObj.keyCodeVal = keyCode;
            if (evtObj.keyCode !== keyCode) {
                console.log("keyCode " + evtObj.keyCode + " 和 (" + evtObj.which + ") 不匹配");
            }
        }
        el.dispatchEvent(evtObj);
    } else if (doc.createEventObject) {//IE 浏览器下模拟事件
        evtObj = doc.createEventObject();
        evtObj.keyCode = keyCode;
        el.fireEvent('on' + evtType, evtObj);
    }
}

function KeyboardEventsTest() {
    var textbox = document.getElementById("myText");
    // fireKeyEvent(textbox, 'keydown', 65);
//     //以DOM3 级方式创建事件对象
//     if (document.implementation.hasFeature("KeyboardEvents", "3.0")) {
//         event = document.createEvent("KeyboardEvent");
// //初始化事件对象
//         event.initKeyboardEvent("keydown", true, true, document.defaultView, "a",
//             0, "Shift", 0);
//     }
// //触发事件
//     textbox.dispatchEvent(event);

//     var e = jQuery.Event("keypress");//模拟一个键盘事件
//     e.keyCode = 65;//keyCode=8是空格
//     $(this).trigger(e);//模拟按下空格键
}

// imageLoadTest();
// scriptLoadTest();
linkLoadTest();
// unloadTest();
// resizeTest();
scrollTest();
// clientXYTest();
// pageXYTest();
// keyTest();
// mouseoutTest();
// getButtonTest();
mousewheelTest();
// keyupTest();
keypressTest();
// removeTest();
// appendChildTest();
contextmenuTest();
// beforeunloadTest();
deviceorientationTest();
// touchTest();
gestureTest();